package cn.fxxk.modular.system.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;

import cn.fxxk.core.common.exception.BizExceptionEnum;
import cn.fxxk.core.reqres.response.ResponseData;
import cn.fxxk.core.util.BigDecimalUtil;
import cn.fxxk.kernel.model.exception.ServiceException;

@Controller
@RequestMapping("/upload")
public class UploadFileController {
	
	
	@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
	@ResponseBody
    public ResponseData uoloadFile(@RequestParam("file") MultipartFile file) {
		
		// 首先校验图片格式
        ArrayList<String> imageType = Lists.newArrayList("jpg","jpeg", "png", "bmp", "gif");
        // 获取文件名，带后缀
        String originalFilename = file.getOriginalFilename();
        // 获取文件的后缀格式
        String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
        if (imageType.contains(fileSuffix)) {
            // 只有当满足图片格式时才进来，重新赋图片名，防止出现名称重复的情况
            String newFileName = UUID.randomUUID() + originalFilename;
            // 该方法返回的为当前项目的工作目录，即在哪个地方启动的java线程
            String dirPath = "/www/wwwroot/uploadFile/";
            String path = "uploadImg" + File.separator + newFileName;
            File destFile = new File(dirPath + path);
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }
            try {
                file.transferTo(destFile);
                // 将相对路径返回给前端
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("url", "http://www.ybbjigui.com/pictures/" + path);
                map.put("fileName", originalFilename);
                map.put("fileSize", BigDecimalUtil.div(file.getSize(), 1000) );
                map.put("fileType", fileSuffix);
                return ResponseData.success(map);
            } catch (IOException e) {
            	throw new ServiceException(BizExceptionEnum.FILE_READING_ERROR);
            }
        } else {
            // 非法文件
            throw new ServiceException(BizExceptionEnum.FILE_READING_ERROR);
        }
    }
}
